class PopupManager {
  constructor() {
    this.currentSession = null;
    this.allSessions = [];
    this.selectedColor = '#4285f4';
    this.init();
  }

  // 安全的消息发送方法，支持重试
  async sendMessage(message, timeout = 5000, retries = 3) {
    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        console.log(`Popup: 发送消息尝试 ${attempt}/${retries}:`, message.action);
        
        const response = await new Promise((resolve, reject) => {
          const timer = setTimeout(() => {
            reject(new Error('消息发送超时'));
          }, timeout);

          try {
            chrome.runtime.sendMessage(message, (response) => {
              clearTimeout(timer);
              
              if (chrome.runtime.lastError) {
                const error = chrome.runtime.lastError.message;
                console.log(`Popup: 消息发送失败 (尝试 ${attempt}):`, error);
                
                // 如果是端口关闭错误，可以重试
                if (error.includes('message port closed') || error.includes('receiving end does not exist')) {
                  reject(new Error(error));
                } else {
                  reject(new Error(error));
                }
              } else {
                resolve(response);
              }
            });
          } catch (error) {
            clearTimeout(timer);
            reject(error);
          }
        });
        
        console.log(`Popup: 消息发送成功 (尝试 ${attempt}):`, response);
        return response;
        
      } catch (error) {
        console.log(`Popup: 消息发送失败 (尝试 ${attempt}/${retries}):`, error.message);
        
        // 如果是最后一次尝试，抛出错误
        if (attempt === retries) {
          throw error;
        }
        
        // 如果是端口关闭错误，等待一段时间后重试（让 Service Worker 重新激活）
        if (error.message.includes('message port closed') || 
            error.message.includes('receiving end does not exist')) {
          console.log(`Popup: 等待 ${attempt * 500}ms 后重试...`);
          await new Promise(resolve => setTimeout(resolve, attempt * 500));
        } else {
          // 其他错误直接抛出
          throw error;
        }
      }
    }
  }

  async init() {
    console.log('Popup: 开始初始化');
    
    // 检查扩展上下文
    if (!chrome.runtime || !chrome.runtime.sendMessage) {
      console.error('Popup: Chrome 扩展 API 不可用');
      return;
    }
    
    await this.loadSessions();
    this.setupEventListeners();
    this.updateUI();
    
    console.log('Popup: 初始化完成');
  }

  async loadSessions(retryCount = 0) {
    try {
      console.log('Popup: 开始加载会话，重试次数:', retryCount);
      const response = await this.sendMessage({ action: 'getSessions' });
      console.log('Popup: getSessions 响应:', response);
      
      if (response && response.success) {
        this.allSessions = response.sessions;
        console.log('Popup: 加载了', this.allSessions.length, '个会话');
        
        // 获取当前活动会话
        const activeTab = await this.getCurrentTab();
        if (activeTab) {
          const sessionResponse = await this.sendMessage({
            action: 'getCurrentSession',
            tabId: activeTab.id
          });
          console.log('Popup: getCurrentSession 响应:', sessionResponse);
          
          if (sessionResponse && sessionResponse.success) {
            this.currentSession = sessionResponse.session;
          }
        }
      } else if (response && response.error && response.error.includes('初始化中') && retryCount < 3) {
        // 如果扩展正在初始化，等待后重试
        console.log('Popup: 扩展正在初始化，等待重试...');
        setTimeout(() => this.loadSessions(retryCount + 1), 1000);
        return;
      } else {
        // 如果没有响应或其他错误，初始化为空数组
        console.warn('Popup: 加载会话失败，响应:', response);
        this.allSessions = [];
        this.currentSession = null;
      }
    } catch (error) {
      console.error('Popup: 加载会话异常:', error);
      if (retryCount < 3) {
        // 网络错误等，也尝试重试
        console.log('Popup: 将在1秒后重试...');
        setTimeout(() => this.loadSessions(retryCount + 1), 1000);
        return;
      }
      this.allSessions = [];
      this.currentSession = null;
    }
  }

  async getCurrentTab() {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    return tabs[0];
  }

  setupEventListeners() {
    // Settings button
    document.getElementById('settingsBtn').addEventListener('click', () => {
      chrome.runtime.openOptionsPage();
    });

    // Create session from current page button
    document.getElementById('createSessionFromPageBtn').addEventListener('click', () => {
      this.showModal('quickSessionModal');
    });

    // New session button
    document.getElementById('newSessionBtn').addEventListener('click', () => {
      this.showModal('newSessionModal');
    });

    // Switch session button
    document.getElementById('switchSessionBtn').addEventListener('click', () => {
      this.showSwitchSessionModal();
    });

    // Quick actions
    document.getElementById('openUrlBtn').addEventListener('click', () => {
      this.showOpenUrlModal();
    });

    document.getElementById('importSessionBtn').addEventListener('click', () => {
      this.importSessions();
    });

    document.getElementById('exportSessionBtn').addEventListener('click', () => {
      this.exportSessions();
    });

    // Modal controls
    this.setupModalEventListeners();
    
    // Form submissions
    this.setupFormEventListeners();

    // Color picker
    this.setupColorPicker();

    // Proxy toggle
    document.getElementById('enableProxy').addEventListener('change', (e) => {
      const proxyConfig = document.getElementById('proxyConfig');
      const proxyHost = document.getElementById('proxyHost');
      const proxyPort = document.getElementById('proxyPort');
      
      if (e.target.checked) {
        proxyConfig.style.display = 'block';
        proxyHost.setAttribute('required', 'required');
        proxyPort.setAttribute('required', 'required');
      } else {
        proxyConfig.style.display = 'none';
        proxyHost.removeAttribute('required');
        proxyPort.removeAttribute('required');
      }
    });
  }

  setupModalEventListeners() {
    // Close modal buttons
    document.querySelectorAll('.modal-close, .btn.secondary').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const modal = e.target.closest('.modal');
        if (modal) {
          this.hideModal(modal.id);
        }
      });
    });

    // Close modal on backdrop click
    document.querySelectorAll('.modal').forEach(modal => {
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          this.hideModal(modal.id);
        }
      });
    });
  }

  setupFormEventListeners() {
    // New session form
    document.getElementById('newSessionForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      await this.createNewSession();
    });

    // Quick session form
    document.getElementById('quickSessionForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      await this.createSessionFromCurrentPage();
    });

    // Open URL form
    document.getElementById('openUrlForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      await this.openUrlInSession();
    });
  }

  setupColorPicker() {
    // Setup color picker for both modals
    document.querySelectorAll('.color-picker').forEach(picker => {
      const colorOptions = picker.querySelectorAll('.color-option');
      
      colorOptions.forEach(option => {
        const color = option.dataset.color;
        option.style.backgroundColor = color;
        
        option.addEventListener('click', () => {
          // Remove selected class from all options in this picker
          colorOptions.forEach(opt => opt.classList.remove('selected'));
          option.classList.add('selected');
          this.selectedColor = color;
        });
      });

      // Select default color for this picker
      const firstColorOption = colorOptions[0];
      if (firstColorOption) {
        firstColorOption.classList.add('selected');
        this.selectedColor = firstColorOption.dataset.color;
      }
    });
  }

  async createNewSession() {
    const form = document.getElementById('newSessionForm');
    const formData = new FormData(form);
    
    const sessionName = formData.get('sessionName') || `会话 ${Date.now()}`;
    
    const config = {
      name: sessionName.trim(),
      color: this.selectedColor || '#4285f4',
      fingerprintProtection: document.getElementById('fingerprintProtection').checked
    };

    // Add proxy configuration if enabled
    if (document.getElementById('enableProxy').checked) {
      const proxyHost = document.getElementById('proxyHost').value.trim();
      const proxyPort = document.getElementById('proxyPort').value.trim();
      
      if (!proxyHost || !proxyPort) {
        alert('启用代理时，主机地址和端口是必填项。');
        return;
      }
      
      config.proxy = {
        enabled: true,
        type: document.getElementById('proxyType').value,
        host: proxyHost,
        port: parseInt(proxyPort),
        username: document.getElementById('proxyUsername').value.trim() || null,
        password: document.getElementById('proxyPassword').value.trim() || null
      };
    }

    try {
      console.log('Popup: 开始创建会话，配置:', config);
      
      // 先尝试 ping 一下 background script 确保它是活跃的
      try {
        console.log('Popup: 发送 ping 测试连接...');
        await this.sendMessage({ action: 'ping' }, 2000, 1);
        console.log('Popup: ping 成功，background script 正常');
      } catch (pingError) {
        console.log('Popup: ping 失败，background script 可能未激活:', pingError.message);
        // 即使 ping 失败也继续尝试创建会话，因为发送消息时可能会激活 Service Worker
      }
      
      const response = await this.sendMessage({
        action: 'createSession',
        config: config
      });

      console.log('Popup: 收到创建会话响应:', response);

      if (response && response.success) {
        console.log('Popup: 会话创建成功');
        this.hideModal('newSessionModal');
        form.reset();
        
        // Reset proxy configuration visibility
        document.getElementById('proxyConfig').style.display = 'none';
        document.getElementById('proxyHost').removeAttribute('required');
        document.getElementById('proxyPort').removeAttribute('required');
        
        // Reset color selection
        document.querySelectorAll('.color-option').forEach(opt => 
          opt.classList.remove('selected')
        );
        const firstColorOption = document.querySelector('.color-option');
        if (firstColorOption) {
          firstColorOption.classList.add('selected');
          this.selectedColor = firstColorOption.dataset.color;
        }
        
        await this.loadSessions();
        this.updateUI();
        
        // 在新标签页中打开新会话（而不是切换当前标签页）
        await this.sendMessage({
          action: 'openInSession',
          url: 'chrome://newtab/',
          sessionId: response.session.id
        });
      } else {
        console.error('Popup: 创建会话失败，响应:', response);
        const errorMessage = response && response.error ? response.error : '未知错误';
        alert(`创建会话失败：${errorMessage}`);
      }
    } catch (error) {
      console.error('Popup: 创建会话异常:', error);
      
      let errorMessage = error.message;
      
      // 根据错误类型提供更友好的错误信息
      if (error.message.includes('message port closed')) {
        errorMessage = '扩展服务暂时不可用，请重新打开扩展弹窗重试';
      } else if (error.message.includes('receiving end does not exist')) {
        errorMessage = '扩展后台服务未响应，请重新加载扩展后重试';
      } else if (error.message.includes('消息发送超时')) {
        errorMessage = '请求超时，请检查网络连接后重试';
      }
      
      alert(`创建会话失败：${errorMessage}`);
    }
  }

  async createSessionFromCurrentPage() {
    const form = document.getElementById('quickSessionForm');
    const formData = new FormData(form);
    
    const sessionName = formData.get('quickSessionName') || `会话 ${Date.now()}`;
    
    const config = {
      name: sessionName.trim(),
      color: this.selectedColor || '#4285f4',
      fingerprintProtection: true // 默认启用指纹保护
    };

    try {
      console.log('Popup: 开始从当前页面创建会话，配置:', config);
      
      // 先尝试 ping 一下 background script 确保它是活跃的
      try {
        console.log('Popup: 发送 ping 测试连接...');
        await this.sendMessage({ action: 'ping' }, 2000, 1);
        console.log('Popup: ping 成功，background script 正常');
      } catch (pingError) {
        console.log('Popup: ping 失败，background script 可能未激活:', pingError.message);
        // 即使 ping 失败也继续尝试创建会话
      }
      
      const response = await this.sendMessage({
        action: 'createSessionFromCurrentPage',
        config: config
      });

      console.log('Popup: 收到从当前页面创建会话响应:', response);

      if (response && response.success) {
        console.log('Popup: 从当前页面创建会话成功');
        this.hideModal('quickSessionModal');
        form.reset();
        
        // Reset color selection
        document.querySelectorAll('#quickColorPicker .color-option').forEach(opt => 
          opt.classList.remove('selected')
        );
        const firstColorOption = document.querySelector('#quickColorPicker .color-option');
        if (firstColorOption) {
          firstColorOption.classList.add('selected');
          this.selectedColor = firstColorOption.dataset.color;
        }
        
        await this.loadSessions();
        this.updateUI();
        
        // 显示成功消息
        const successMessage = `会话 "${response.session.name}" 已创建，新标签页已打开`;
        console.log('Popup:', successMessage);
        
        // 关闭弹窗
        window.close();
      } else {
        console.error('Popup: 从当前页面创建会话失败，响应:', response);
        const errorMessage = response && response.error ? response.error : '未知错误';
        alert(`创建会话失败：${errorMessage}`);
      }
    } catch (error) {
      console.error('Popup: 从当前页面创建会话异常:', error);
      
      let errorMessage = error.message;
      
      // 根据错误类型提供更友好的错误信息
      if (error.message.includes('message port closed')) {
        errorMessage = '扩展服务暂时不可用，请重新打开扩展弹窗重试';
      } else if (error.message.includes('receiving end does not exist')) {
        errorMessage = '扩展后台服务未响应，请重新加载扩展后重试';
      } else if (error.message.includes('消息发送超时')) {
        errorMessage = '请求超时，请检查网络连接后重试';
      }
      
      alert(`创建会话失败：${errorMessage}`);
    }
  }

  async openUrlInSession() {
    const url = document.getElementById('urlInput').value;
    const sessionId = document.getElementById('urlSessionSelect').value;

    if (!url || !sessionId) {
      alert('请输入网址并选择一个会话。');
      return;
    }

    try {
      const response = await this.sendMessage({
        action: 'openInSession',
        url: url,
        sessionId: sessionId
      });

      if (response && response.success) {
        this.hideModal('openUrlModal');
        document.getElementById('openUrlForm').reset();
      } else {
        alert('打开链接失败，请重试。');
      }
    } catch (error) {
      console.error('在会话中打开链接失败:', error);
      alert('打开链接失败，请重试。');
    }
  }

  showSwitchSessionModal() {
    const modal = document.getElementById('switchSessionModal');
    const sessionsList = document.getElementById('switchSessionsList');
    
    sessionsList.innerHTML = '';
    
    this.allSessions.forEach(session => {
      const sessionCard = document.createElement('div');
      sessionCard.className = 'session-card';
      sessionCard.innerHTML = `
        <div class="session-card-color" style="background-color: ${session.color}"></div>
        <div class="session-card-name">${session.name}</div>
        <div class="session-card-tabs">${session.tabs.length} 个标签页</div>
      `;
      
      sessionCard.addEventListener('click', async () => {
        const currentTab = await this.getCurrentTab();
        if (currentTab) {
          await this.sendMessage({
            action: 'switchSession',
            sessionId: session.id
          });
          window.close();
        }
      });
      
      sessionsList.appendChild(sessionCard);
    });
    
    this.showModal('switchSessionModal');
  }

  showOpenUrlModal() {
    const sessionSelect = document.getElementById('urlSessionSelect');
    sessionSelect.innerHTML = '<option value="">Select a session</option>';
    
    this.allSessions.forEach(session => {
      const option = document.createElement('option');
      option.value = session.id;
      option.textContent = session.name;
      sessionSelect.appendChild(option);
    });
    
    this.showModal('openUrlModal');
  }

  async deleteSession(sessionId) {
    if (!confirm('确定要删除这个会话吗？该会话中的所有标签页都将被关闭。')) {
      return;
    }

    try {
      const response = await this.sendMessage({
        action: 'deleteSession',
        sessionId: sessionId
      });

      if (response && response.success) {
        await this.loadSessions();
        this.updateUI();
      } else {
        alert('删除会话失败，请重试。');
      }
    } catch (error) {
      console.error('删除会话失败:', error);
      alert('删除会话失败，请重试。');
    }
  }

  async switchToSession(sessionId) {
    const currentTab = await this.getCurrentTab();
    if (currentTab) {
      try {
        await this.sendMessage({
          action: 'switchSession',
          sessionId: sessionId
        });
        window.close();
      } catch (error) {
              console.error('切换会话失败:', error);
      alert('切换会话失败，请重试。');
      }
    }
  }

  updateUI() {
    this.updateCurrentSession();
    this.updateSessionsList();
    this.updateSessionCount();
  }

  updateCurrentSession() {
    const currentSessionEl = document.getElementById('currentSession');
    const sessionColor = document.getElementById('currentSessionColor');
    const sessionName = document.getElementById('currentSessionName');
    const sessionTabs = document.getElementById('currentSessionTabs');

    if (this.currentSession) {
      sessionColor.style.backgroundColor = this.currentSession.color;
      sessionName.textContent = this.currentSession.name;
      sessionTabs.textContent = `${this.currentSession.tabs.length} 个标签页`;
    } else {
      sessionColor.style.backgroundColor = '#ccc';
              sessionName.textContent = '无活动会话';
      sessionTabs.textContent = '0 个标签页';
    }
  }

  updateSessionsList() {
    const sessionsList = document.getElementById('sessionsList');
    sessionsList.innerHTML = '';

    if (this.allSessions.length === 0) {
      const emptyState = document.createElement('div');
      emptyState.className = 'empty-state';
      emptyState.innerHTML = `
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
        </svg>
        <h3>No Sessions</h3>
        <p>Create your first session to get started with multi-account management.</p>
      `;
      sessionsList.appendChild(emptyState);
      return;
    }

    this.allSessions.forEach(session => {
      const sessionItem = document.createElement('div');
      sessionItem.className = 'session-item';
      if (this.currentSession && session.id === this.currentSession.id) {
        sessionItem.classList.add('active');
      }

      sessionItem.innerHTML = `
        <div class="session-item-info">
          <div class="session-item-color" style="background-color: ${session.color}"></div>
          <div class="session-item-details">
            <div class="session-item-name">${session.name}</div>
            <div class="session-item-meta">
              ${session.tabs.length} 个标签页 • ${this.formatDate(session.lastUsed)}
            </div>
          </div>
        </div>
        <div class="session-item-actions">
          <button class="session-action-btn" title="Switch to session">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z"/>
            </svg>
          </button>
          <button class="session-action-btn danger" title="Delete session">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
              <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
            </svg>
          </button>
        </div>
      `;

      // Add event listeners
      const switchBtn = sessionItem.querySelector('.session-action-btn:not(.danger)');
      const deleteBtn = sessionItem.querySelector('.session-action-btn.danger');

      switchBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        this.switchToSession(session.id);
      });

      deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        this.deleteSession(session.id);
      });

      sessionItem.addEventListener('click', () => {
        this.switchToSession(session.id);
      });

      sessionsList.appendChild(sessionItem);
    });
  }

  updateSessionCount() {
    const sessionCount = document.getElementById('sessionCount');
    sessionCount.textContent = this.allSessions.length;
  }

  formatDate(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return `${Math.floor(diff / 86400000)}d ago`;
  }

  showModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.add('show');
  }

  hideModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('show');
  }

  async importSessions() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    
    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      
      try {
        const content = await file.text();
        const sessions = JSON.parse(content);
        
        for (const sessionData of sessions) {
          await this.sendMessage({
            action: 'createSession',
            config: sessionData
          });
        }
        
        await this.loadSessions();
        this.updateUI();
                  alert(`成功导入 ${sessions.length} 个会话。`);
      } catch (error) {
              console.error('导入会话失败:', error);
      alert('导入会话失败，请检查文件格式。');
      }
    };
    
    input.click();
  }

  async exportSessions() {
    try {
      const exportData = this.allSessions.map(session => ({
        name: session.name,
        color: session.color,
        proxy: session.proxy,
        userAgent: session.userAgent,
        fingerprintProtection: session.fingerprintProtection
      }));
      
      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json'
      });
      
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `sessionbox-sessions-${new Date().toISOString().split('T')[0]}.json`;
      a.click();
      
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出会话失败:', error);
      alert('导出会话失败，请重试。');
    }
  }
}

// Initialize popup when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  new PopupManager();
}); 